package main

import (
	"log"
	"net/http"

	"github.com/yourusername/apijson-auth/config"
	"github.com/yourusername/apijson-auth/database"
	"github.com/yourusername/apijson-auth/handler"
	"github.com/yourusername/apijson-auth/middleware"

	"github.com/gorilla/mux"
)

func main() {
	// 加载配置
	config.LoadConfig()

	// 初始化数据库
	if err := database.InitDB(); err != nil {
		log.Fatalf("Database initialization failed: %v", err)
	}

	// 创建路由
	r := mux.NewRouter()

	// 认证路由
	r.HandleFunc("/login", handler.Login).Methods("POST")
	r.HandleFunc("/logout", handler.Logout).Methods("POST")

	// CRUD路由 (使用认证中间件)
	crudHandler := &handler.Handler{DB: database.DB}
	api := r.PathPrefix("/api").Subrouter()
	api.Use(middleware.AuthMiddleware)

	api.HandleFunc("/get", crudHandler.Get).Methods("GET")
	api.HandleFunc("/post", crudHandler.Post).Methods("POST")
	api.HandleFunc("/put", crudHandler.Put).Methods("PUT")
	api.HandleFunc("/delete", crudHandler.Delete).Methods("DELETE")

	// 启动服务器
	log.Printf("Server starting on port %s", config.AppConfig.Server.Port)
	log.Fatal(http.ListenAndServe(":"+config.AppConfig.Server.Port, r))
}
